import { Component } from 'react'
import { View, Button, Text, Image, Map } from '@tarojs/components'
import { observer, inject } from 'mobx-react'
import Taro from '@tarojs/taro'
import QQMapWX from '../../utils/qqmap-wx-jssdk'
import mapConfig from '../../config/map.config'

import './index.less'

@inject('store')
@observer
class Index extends Component {
  componentDidMount() {
    const { destinationsStore } = this.props.store
    destinationsStore.loadDestinations()
    
    // 获取用户位置
    Taro.getLocation({
      type: 'gcj02',
      success: (res) => {
        this.setState({
          latitude: res.latitude,
          longitude: res.longitude,
          scale: 4
        })
        
        // 更新地图标记
        this.updateMarkers()
        
        // 计算距离
        this.calculateDistances(res.latitude, res.longitude)
      },
      fail: () => {
        // 默认显示世界地图
        this.setState({
          latitude: mapConfig.initialRegion.latitude,
          longitude: mapConfig.initialRegion.longitude,
          scale: mapConfig.initialRegion.scale
        })
        
        // 更新地图标记
        this.updateMarkers()
      }
    })
  }

  componentDidShow() { }

  componentDidHide() { }
  
  constructor(props) {
    super(props)
    this.state = {
      latitude: mapConfig.initialRegion.latitude,
      longitude: mapConfig.initialRegion.longitude,
      scale: mapConfig.initialRegion.scale,
      markers: [],
      mapStyle: mapConfig.mapStyle,
      polyline: [],
      distance: {}
    }
    
    // 初始化腾讯地图SDK
    this.qqmapsdk = new QQMapWX({
      key: mapConfig.key
    })
  }
  
  // 更新地图标记
  updateMarkers() {
    const { destinationsStore: { destinations } } = this.props.store
    
    const markers = destinations.map((dest, index) => ({
      id: dest.id,
      latitude: dest.latitude,
      longitude: dest.longitude,
      title: dest.name,
      iconPath: dest.visited ? '/assets/marker-visited.svg' : '/assets/marker-unvisited.svg',
      width: mapConfig.markerSettings.width,
      height: mapConfig.markerSettings.height,
      callout: {
        content: `${dest.name}\n${dest.country}\n${dest.visited ? '✅ 已打卡' : '⭐ 未打卡'}`,
        color: mapConfig.markerSettings.callout.color,
        fontSize: mapConfig.markerSettings.callout.fontSize,
        fontWeight: mapConfig.markerSettings.callout.fontWeight,
        borderRadius: mapConfig.markerSettings.callout.borderRadius,
        bgColor: mapConfig.markerSettings.callout.bgColor,
        padding: mapConfig.markerSettings.callout.padding,
        display: mapConfig.markerSettings.callout.display,
        borderWidth: mapConfig.markerSettings.callout.borderWidth,
        borderColor: mapConfig.markerSettings.callout.borderColor,
        textAlign: mapConfig.markerSettings.callout.textAlign,
        boxShadow: mapConfig.markerSettings.callout.boxShadow
      }
    }))
    
    this.setState({ markers })
  }
  
  // 计算用户与目的地之间的距离
  calculateDistances(latitude, longitude) {
    const { destinationsStore: { destinations } } = this.props.store
    
    if (destinations.length === 0) return
    
    // 构建目的地位置数组
    const to = destinations.map(dest => `${dest.latitude},${dest.longitude}`).join(';')
    
    // 使用腾讯地图SDK计算距离
    this.qqmapsdk.calculateDistance({
      from: {
        latitude,
        longitude
      },
      to,
      success: (res) => {
        if (res.status === 0 && res.result && res.result.elements) {
          const distance = {}
          res.result.elements.forEach((item, index) => {
            if (item.distance !== -1) {
              distance[destinations[index].id] = {
                distance: item.distance, // 单位：米
                duration: item.duration  // 单位：秒
              }
            }
          })
          
          this.setState({ distance })
        }
      },
      fail: (error) => {
        console.error('距离计算失败', error)
      }
    })
  }
  
  // 地图标记点击事件
  handleMarkerTap = (e) => {
    const markerId = e.markerId
    const { destinationsStore: { destinations } } = this.props.store
    const destination = destinations.find(dest => dest.id === markerId)
    const { distance } = this.state
    
    if (destination) {
      // 格式化距离显示
      let distanceText = '距离未知'
      if (distance[destination.id]) {
        const dist = distance[destination.id].distance
        if (dist < 1000) {
          distanceText = `距离您: ${dist}米`
        } else {
          distanceText = `距离您: ${(dist / 1000).toFixed(1)}公里`
        }
      }
      
      Taro.showModal({
        title: destination.name,
        content: `${destination.country}\n${destination.description}\n${distanceText}\n状态: ${destination.visited ? '已打卡' : '未打卡'}`,
        confirmText: destination.visited ? '取消打卡' : '打卡',
        cancelText: '关闭',
        success: (res) => {
          if (res.confirm) {
            this.props.store.destinationsStore.toggleVisited(destination.id)
            this.updateMarkers()
          }
        }
      })
    }
  }

  // 跳转到目的地列表页
  navigateToDestinations = () => {
    Taro.navigateTo({
      url: '/pages/destinations/index'
    })
  }

  componentDidUpdate(prevProps) {
    const { destinationsStore: { destinations } } = this.props.store
    const prevDestinations = prevProps.store.destinationsStore.destinations
    
    if (destinations !== prevDestinations) {
      this.updateMarkers()
    }
  }
  
  render() {
    const { destinationsStore: { destinations } } = this.props.store
    const visitedCount = destinations.filter(dest => dest.visited).length
    const unvisitedCount = destinations.length - visitedCount
    const { latitude, longitude, scale, markers, mapStyle } = this.state

    return (
      <View className='index'>
        <View className='header'>
          <Text className='title'>行记</Text>
          <Text className='subtitle'>记录我们的旅行足迹</Text>
        </View>
        
        <View className='map-container'>
          <Map
            className='map'
            latitude={latitude}
            longitude={longitude}
            scale={scale}
            markers={markers}
            showLocation
            onMarkerTap={this.handleMarkerTap}
            setting={{
              showCompass: true,
              enableRotate: true,
              enableOverlooking: true,
              enableSatellite: mapStyle === 'satellite',
              enableTraffic: false
            }}
            id="myMap"
          />
        </View>

        <View className='stats'>
          <View className='stat-item'>
            <Text className='stat-number'>{destinations.length}</Text>
            <Text className='stat-label'>目的地总数</Text>
          </View>
          <View className='stat-item'>
            <Text className='stat-number'>{visitedCount}</Text>
            <Text className='stat-label'>已打卡数量</Text>
          </View>
          <View className='stat-item'>
            <Text className='stat-number'>{unvisitedCount}</Text>
            <Text className='stat-label'>待打卡数量</Text>
          </View>
          <View className='stat-item'>
            <Text className='stat-number'>{destinations.length > 0 ? (visitedCount / destinations.length * 100).toFixed(0) : 0}%</Text>
            <Text className='stat-label'>完成率</Text>
          </View>
        </View>

        {/* <View className='actions'>
          <Button className='action-btn' onClick={this.navigateToDestinations}>
            查看目的地列表
          </Button>
        </View> */}
      </View>
    )
  }
}

export default Index
